package kr.co.solosoft.nextdayjob;

import java.util.ArrayList;
import kr.co.solosoft.nextdayjob.data.Config;
import kr.co.solosoft.nextdayjob.data.JobXmlParser;
import kr.co.solosoft.nextdayjob.data.RequestMethod;
import kr.co.solosoft.nextdayjob.data.RestClient;
import kr.co.solosoft.nextdayjob.data.ResultData;
import kr.co.solosoft.nextdayjob.data.SerchData;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class NextDayJobActivity extends Activity 
{
	private static final String API_KEY = "60E85A00C76D4C86CE666683D6FAF667FA5EC435";
	private static final int COUNT = 10;
	private EditText txtSerch;
	private Spinner spinArea;
	private SerchData data;
	private Button btnSerch;
	private ArrayList<ResultData> resultArray;
	private ListView serchList;
	private SerchListDataAdapter adapter;
	private int startNo;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        txtSerch = (EditText)findViewById(R.id.txtSerch);
        spinArea = (Spinner)findViewById(R.id.spinArea);
        btnSerch = (Button)findViewById(R.id.btnSerch);
        serchList = (ListView)findViewById(R.id.serchList);
        

        data = new SerchData();
        
        serchList.setOnScrollListener(new ListView.OnScrollListener()
		{
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState)
			{
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount)
			{
				if(totalItemCount >0 && firstVisibleItem+visibleItemCount ==totalItemCount)
				{
					//끝에오게된경우
					
					RestClient client = new RestClient("http://naeilapi.incruit.com/api/?method=search");
			        client.AddParam("apikey", API_KEY);
			        client.AddParam("start", String.valueOf(COUNT+resultArray.size()));
			        client.AddParam("count", String.valueOf(COUNT));
			        
			        if(data.getSerchText() == null || data.getSerchText().length() == 0)
			        {
			        	//검색어입력 경고창
			        	return;
			        }
			        else
			        {
			        	client.AddParam("q", data.getSerchText());
			        }
			        
			        if(data.getAreaCode() != -1)
			        {
			        	client.AddParam("rgn1", String.valueOf(data.getAreaCode()));
			        }
			        
			        if(data.getMoneyCode() != -1)
			        {
			        	client.AddParam("sry", String.valueOf(data.getMoneyCode()));
			        }
			        
			        if(data.getCareerCode() != -1)
			        {
			        	client.AddParam("crr", String.valueOf(data.getCareerCode()));
			        }
			        
			        if(data.getAcademicCode() != -1)
			        {
			        	client.AddParam("schol", String.valueOf(data.getAcademicCode()));
			        }

			        if(data.getCompanyCode() != -1)
			        {
			        	client.AddParam("scale", String.valueOf(data.getCompanyCode()));
			        }
			        
			        if(data.getWorkTypeCode() != -1)
			        {
			        	client.AddParam("epty", String.valueOf(data.getWorkTypeCode()));
			        }
			        
			        try 
			        {
			            client.Execute(RequestMethod.GET);
			        } 
			        catch (Exception e)
			        { 
			            e.printStackTrace();
			        }

			        String response = client.getResponse();
			        JobXmlParser jobParser = new JobXmlParser(response);
			        
			        ArrayList<ResultData> tempArray = jobParser.getResultArray();
			        resultArray.addAll(tempArray);
			        adapter.notifyDataSetChanged();
				}
			}
		});
        
       
        btnSerch.setOnClickListener(new Button.OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				data.setSerchText(txtSerch.getText().toString());
				
				RestClient client = new RestClient("http://naeilapi.incruit.com/api/?method=search");
		        client.AddParam("apikey", API_KEY);
		        client.AddParam("count", String.valueOf(COUNT));
		        if(data.getSerchText() == null || data.getSerchText().length() == 0)
		        {
		        	//검색어입력 경고창
		        	return;
		        }
		        else
		        {
		        	client.AddParam("q", data.getSerchText());
		        }
		        
		        if(data.getAreaCode() != -1)
		        {
		        	client.AddParam("rgn1", String.valueOf(data.getAreaCode()));
		        }
		        
		        if(data.getMoneyCode() != -1)
		        {
		        	client.AddParam("sry", String.valueOf(data.getMoneyCode()));
		        }
		        
		        if(data.getCareerCode() != -1)
		        {
		        	client.AddParam("crr", String.valueOf(data.getCareerCode()));
		        }
		        
		        if(data.getAcademicCode() != -1)
		        {
		        	client.AddParam("schol", String.valueOf(data.getAcademicCode()));
		        }

		        if(data.getCompanyCode() != -1)
		        {
		        	client.AddParam("scale", String.valueOf(data.getCompanyCode()));
		        }
		        
		        if(data.getWorkTypeCode() != -1)
		        {
		        	client.AddParam("epty", String.valueOf(data.getWorkTypeCode()));
		        }
		        
		        try 
		        {
		            client.Execute(RequestMethod.GET);
		        } 
		        catch (Exception e)
		        { 
		            e.printStackTrace();
		        }

		        String response = client.getResponse();
		        JobXmlParser jobParser = new JobXmlParser(response);
		        
		        resultArray = jobParser.getResultArray();
		        
		        adapter = new SerchListDataAdapter(NextDayJobActivity.this, R.layout.result_item, resultArray);
		        serchList.setAdapter(adapter);
			}
		});
        
        spinArea.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()
		{

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,int position, long id)
			{
				data.setAreaCode(Config.areaCode[position]);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent)
			{
				data.setAreaCode(-1);
			}
		});
        
        txtSerch.setOnEditorActionListener(new EditText.OnEditorActionListener()
		{
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
			{
				if(actionId == EditorInfo.IME_ACTION_DONE)
				{
					data.setSerchText(txtSerch.getText().toString());
				}
				return false;
			}
		});
    }
    
    private class SerchListDataAdapter extends BaseAdapter
	{
		private LayoutInflater inflater;
		private ArrayList<ResultData> array;
		private int layout;
		
		public SerchListDataAdapter(Context context, int layout, ArrayList<ResultData> array)
		{
			this.layout = layout;
			this.array = array;
			this.inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		@Override
		public int getCount()
		{
			return array.size();
		}

		@Override
		public Object getItem(int position)
		{
			
			return array.get(position);
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			
			if(convertView == null)
				convertView = inflater.inflate(layout, parent, false);
			
			ResultData data = array.get(position);
			
			TextView txtCompany = (TextView)convertView.findViewById(R.id.txtCompany);
			TextView txtTitle = (TextView)convertView.findViewById(R.id.txtTitle);
			TextView txtSubContent = (TextView)convertView.findViewById(R.id.txtSubContent);
			TextView txtSchool = (TextView)convertView.findViewById(R.id.txtSchool);
			TextView txtCareer = (TextView)convertView.findViewById(R.id.txtCareer);
			TextView txtEmploy = (TextView)convertView.findViewById(R.id.txtEmploy);
			TextView txtContent = (TextView)convertView.findViewById(R.id.txtContent);
			TextView txtData = (TextView)convertView.findViewById(R.id.txtData);
			TextView txtEndData = (TextView)convertView.findViewById(R.id.txtEndData);
			TextView txtUrl = (TextView)convertView.findViewById(R.id.txtUrl);
			TextView txtFromUrl = (TextView)convertView.findViewById(R.id.txtFromUrl);
	
			txtCompany.setText(String.format("업체명 : %s", Html.fromHtml(data.getCompanyName())));
			txtTitle.setText(Html.fromHtml(data.getJobTitle()));
			txtSubContent.setText(String.format("급여 : %s | %s | 등록일 : %s", data.getSalaryName(), data.getDetailRegionName(), data.getClDate()));
			txtSchool.setText(String.format("학력조건 : %s", data.getScholName()));
			txtCareer.setText(String.format("경력조건 : %s", data.getCareerName()));
			txtEmploy.setText(String.format("고용형태 : %s", data.getEmployType()));
			txtContent.setText(Html.fromHtml(data.getJonContent()));
			txtData.setText(String.format("모집일 : %s ~ %s", data.getStartDate(), data.getEndDate()));
			txtEndData.setText(String.format("마감일 : %s", data.getEmployLimit()));
			txtUrl.setText(Html.fromHtml("구인정보 : <a href=" + data.getLinkUrl() + ">링크 클릭"));
			txtUrl.setMovementMethod(LinkMovementMethod.getInstance());
			txtFromUrl.setText(Html.fromHtml("내용출처 : <a href=" + data.getSiteUrl() + ">"+data.getSiteName()));
			txtFromUrl.setMovementMethod(LinkMovementMethod.getInstance());
			
			return convertView;
		}
	}
}